package ru.usu.gv.gui.routing;

import ru.usu.gv.uicomponents.UIEdge;
import ru.usu.gv.uicomponents.UIGraph;
import ru.usu.gv.utils.geometry.Polygon;
import ru.usu.gv.utils.geometry.Polyline;

import javax.vecmath.Point2d;

import java.util.List;

/**
 * @author spupyrev
 * 28.10.2009
 * 
 * Router between two nodes
 */
public class EdgeRouter
{
	private UIGraph uiGraph;
	private UIEdge uiEdge;

	public EdgeRouter(UIGraph uiGraph, UIEdge uiEdge)
	{
		this.uiGraph = uiGraph;
		this.uiEdge = uiEdge;
	}

	public void route()
	{
		System.out.println("routing " + uiEdge + " edge...");

		//try straight line

		VisibilityGraph visibilityGraph = buildVisibilityGraph();
		//visibilityGraph.debugShow();
		//if (1 == 1)
		//	return;
		Polyline polyline = getShortestPolyline(visibilityGraph);
		//relax polyline

		uiEdge.getViewItem().setControlPoints(polyline.toControlPoints());
		uiEdge.draw();
		System.out.println("Added " + uiEdge.getViewItem().getControlPoints().length + " control points");
	}

	private VisibilityGraph buildVisibilityGraph()
	{
		List<Polygon> obstacles = new ObstacleCalculator(uiGraph).calculate();
		return new VisibilityGraph(getSource(), getTarget(), obstacles);
	}

	private Polyline getShortestPolyline(VisibilityGraph visibilityGraph)
	{
		return visibilityGraph.getShortestPolyline(getSource(), getTarget());
	}

	private Point2d getSource()
	{
		return new Point2d(uiEdge.getV1().getPosition().x, uiEdge.getV1().getPosition().y);
	}

	private Point2d getTarget()
	{
		return new Point2d(uiEdge.getV2().getPosition().x, uiEdge.getV2().getPosition().y);
	}
}
